package com.ziytek.web.citizen.listener;

import com.google.gson.Gson;
import com.ziytek.web.citizen.config.caffeine.CaffeineUtil;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.event.CommandResponseEvent;
import com.ziytek.web.citizen.model.bean.CommandConfirmation;
import com.ziytek.web.citizen.util.CabinetNoUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author fenghx
 * @version 1.0
 * @className CommandResponseEventListener
 * Description:
 * @date 2025/3/12 20:21
 */

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @__(@Autowired))
public class CommandResponseEventListener {
    private final Gson gson;

    @Async("myAsyncExecutor")
    @EventListener
    public void commandResponseEventListener(CommandResponseEvent event) {
        Assert.notNull(event, "CommandResponseEvent is null");
        Assert.notNull(event.getCommandResponse(), "CommandResponseEvent CommandResponse is null");
        log.info("工步下发上送响应处理CommandResponseEventListener event:{}", gson.toJson(event.getCommandResponse()));

        var commandResponse = event.getCommandResponse();
        var success = commandResponse.getS();
        var cabinetNoNumber = commandResponse.getB();
        var message = commandResponse.getM().toUpperCase();
        if (success == NumConstant.INT_ZERO) {
            log.info("工步下发上送响应失败CommandResponseEventListener failed:{} message:{} boardAddress:{}", success, message, cabinetNoNumber);
            return;
        }

        var cabinetNo = CabinetNoUtil.getCabinetNo(String.valueOf(cabinetNoNumber));
        var key = CaffeineUtil.COMMAND_CONFIRMATION + cabinetNo + CaffeineUtil.CACHE_KEY_CONNECTION_SYMBOL + message;
        CommandConfirmation cf = CaffeineUtil.get(key);
        if (cf == null) {
            log.info("工步下发上送响应未找到缓存CommandResponseEventListener CommandConfirmation no cache:{}", key);
            return;
        }

        // 指令下发结果缓确认缓存
        cf.setSuccess(true);
        CaffeineUtil.set(CaffeineUtil.COMMAND_CONFIRMATION + cabinetNo + CaffeineUtil.CACHE_KEY_CONNECTION_SYMBOL + message, cf, 30);

        log.info("工步下发上送响应处理成功CommandResponseEventListener CommandConfirmation success:{} message:{} boardAddress:{},commandConfirmation:{}", success, message, cabinetNo, gson.toJson(cf));
    }
}
